package com.hsq.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.cookie.CookieStore;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 使用httpclient实现get和post请求
 */
public class HttpDriver {

	public static String doGet(String url) {
		CloseableHttpClient client = HttpClients.createDefault(); // 创建客户端对象
		HttpGet get = new HttpGet(url); // 创建请求对象
		get.setHeader("User-Agent", "PostmanRuntime/7.29.2"); // 有些服务器对客户端有限制防止灌水攻击，所以加上此请求头
		String txt = null;
		CloseableHttpResponse fee_response;
		try {
			fee_response = client.execute(get); // 客户端执行get请求并返回完整的响应（包含响求行、响求头、响求体）

			HttpEntity entity = fee_response.getEntity(); // 获得完整响应中的请求体
			txt = EntityUtils.toString(entity, "utf-8"); // //将响应体转换成字符串类型，并设置响应的编码方式为utf-8的格式以防止中文乱码
			EntityUtils.consume(entity); // 释放资源
			
			fee_response.close(); //断开连接
			client.close();
		} catch (ParseException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return txt;

	}

	
	// 将map类型转换成字符串
	public static String mapToString(Map<String, Object> para) {
		StringBuilder res = new StringBuilder("?");
		for (Entry<String,Object> entry : para.entrySet()) {
			res.append(entry.getKey() + "=" + entry.getValue() + '&');
		}
		return res.substring(0, res.length() - 1);
	}

	
	// 带参数的get请求
	public static String doGet(String url, Map<String, Object> para) {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet get = new HttpGet(url + mapToString(para));
//		get.setHeader("User-Agent", "PostmanRuntime/7.29.2");
		String txt = null;
		CloseableHttpResponse fee_response;
		try {
			fee_response = client.execute(get);

			HttpEntity entity = fee_response.getEntity();

			txt = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			fee_response.close();
			client.close();
		} catch (ParseException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return txt;

	}

	
	public static String doGet(String url, CookieStore cookie) {
		CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookie).build(); // 通过cookie得到相应的client客户端
		HttpGet get = new HttpGet(url);
		String txt = null;
		CloseableHttpResponse fee_response;
		try {
			fee_response = client.execute(get);

			HttpEntity entity = fee_response.getEntity();

			txt = EntityUtils.toString(entity, "utf-8");
			EntityUtils.consume(entity);
			fee_response.close();
			client.close();
		} catch (ParseException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return txt;

	}
	
	

	
//	针对的是请求体Form
	public static String doPost(String url, List<NameValuePair> body) {

		CloseableHttpClient client = HttpClients.createDefault(); // 创建客户端对象client

		String txt = null; 
		HttpPost post = new HttpPost(url); // 创建请求对象post
		
		post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // 设置请求头
		post.setHeader("X-Requested-With", "XMLHttpRequest");
		post.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		post.setEntity(new UrlEncodedFormEntity(body, Charset.forName("utf-8"))); // 设置请求体

		try {
			CloseableHttpResponse response = client.execute(post); // 执行post请求，获得完整的响应（包含响求行、响求头、响求体）
			HttpEntity entity = response.getEntity(); // 获得响应体
			txt = EntityUtils.toString(entity, "utf-8"); // 获得string类型的响应体，并设置响应类型为utf-8以防止中文乱码
			
			EntityUtils.consume(entity); // 释放资源
			
			response.close(); // 断开连接
			client.close();
		} catch (ParseException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return txt;

	}
	
	
	
	// 针对的是带cookie的请求体Form
	// 2022年9月11日重载了该方法，新加
	public static String doPost(String url, List<NameValuePair> body, CookieStore cookie) {

		CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookie).build(); // 创建客户端对象client

		String txt = null; 
		HttpPost post = new HttpPost(url); // 创建请求对象post
		
		post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); // 设置请求头
		post.setHeader("X-Requested-With", "XMLHttpRequest");
		post.setHeader("Accept", "application/json, text/javascript, */*; q=0.01");
		post.setEntity(new UrlEncodedFormEntity(body, Charset.forName("utf-8"))); // 设置请求体

		try {
			CloseableHttpResponse response = client.execute(post); // 执行post请求，获得完整的响应（包含响求行、响求头、响求体）
			HttpEntity entity = response.getEntity(); // 获得响应体
			txt = EntityUtils.toString(entity, "utf-8"); // 获得string类型的响应体，并设置响应类型为utf-8以防止中文乱码
			
			EntityUtils.consume(entity); // 释放资源
			
			response.close(); // 断开连接
			client.close();
		} catch (ParseException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return txt;

	}
	

	
//	针对的是请求体JSON
	public static String doPost(String url, JSONObject body) {
		CloseableHttpClient client = HttpClients.createDefault();
		String txt = null;
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-Type", "application/json"); // 设置请求头
		post.setEntity(new StringEntity(body.toString())); // 设置请求体

		try {
			CloseableHttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			txt = EntityUtils.toString(entity, "utf-8");
			
			EntityUtils.consume(entity);
			response.close();
			client.close();
		} catch (ParseException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return txt;

	}

	
	public static String doPost(String url, JSONObject body, CookieStore cookieStore) {
		CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); // 通过传入的cookie获得相应的客户端对象
		String txt = null;
		HttpPost post = new HttpPost(url);
		post.setHeader("Content-Type", "application/json");
		post.setEntity(new StringEntity(body.toString()));

		try {
			CloseableHttpResponse response = client.execute(post);
			HttpEntity entity = response.getEntity();
			txt = EntityUtils.toString(entity, "utf-8");
			
			EntityUtils.consume(entity);
			response.close();
			client.close();
		} catch (ParseException | IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		return txt;

	}

}
